package com.yueshop.yueshopsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.yueshop.common.to.SkuEsModel;
import com.yueshop.yueshopsearch.conf.YueShopElasticSearchConfig;
import com.yueshop.yueshopsearch.constant.EsConstant;
import com.yueshop.yueshopsearch.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;


@Slf4j
@Service
public class ProductSaveServiceImpl  implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        //将数据批量保存到es中
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //设置索引的id
            indexRequest.id(skuEsModel.getSkuId().toString());
           //设置具体要保存的内容
            String json = JSON.toJSONString(skuEsModel);
            indexRequest.source(json, XContentType.JSON);
            //添加保存请求
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, YueShopElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();

        if(!b){
            log.info("商品上架完成");
        }
        return b;
    }
}
